package com.kenliang.javase.concurrent.thread;

import com.google.common.util.concurrent.*;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.concurrent.*;

/**
 * @author KenLiang
 * @description:
 * @date Created in 3:04 PM 2019/3/27.
 */
public class ThreadPoolExecutorTest {

    public static void main(String[] args) {
        ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator((ThreadPoolExecutor) ThreadPoolExecutorTest.getExecutor(16, 16));
//        listeningExecutorService.execute(() -> {
//            System.out.println("------------a-execute----------");
//        });
        ListenableFuture<Boolean> future = listeningExecutorService.submit(() -> {
            System.out.println("------------a-submit----------");
            return Boolean.TRUE;
        });

        future.addListener(()->{
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        },listeningExecutorService);

        Futures.addCallback(future, new FutureCallback<Boolean>() {
            @Override
            public void onSuccess(@Nullable Boolean result) {
                if (result != null && result.booleanValue()) {
                    System.out.println("---submit --success");
                }
            }

            @Override
            public void onFailure(Throwable t) {
                System.out.println("---submit --failure");
            }
        }, listeningExecutorService);
    }

    public static Executor getExecutor(int threadNum, int queueSize) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(threadNum, threadNum, 0, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(queueSize),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        return threadPoolExecutor;
    }
}


